/**  
  -- The Performance Driven Lime Project -- 

  A self adaptive tuple space for mobile agents and hosts by dynamic
  adapting tuple's replication policy.
  
  Copyright (C) 2008
  Xing Jiankuan, Pan Wenhui
  SAGroup of Tsinghua University

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package sagroup.dracots.testing;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

import lime2.Location;
import lime2.TupleID;
import sagroup.dracots.DracoTS;
import sagroup.dracots.FlatShareTuple;
import sagroup.dracots.ShareTuple;
import sagroup.dracots.TupleType;
import sagroup.util.Util;

/**
 * @author Zheng Xiang
 * 
 */
public class UpdateAgent extends AbstractAgent {

	private long meaninterval;
	//private double percentage;
	private TupleType type;
	private volatile boolean timesup = false;
	private int opCount = 0;
	private DracoTS dts;

	private long mu, sigma;
	
	private long usedTotalTime = 0L; 

	private Logger LOG = Logger.getLogger(this.getClass().getName());

	private HashSet<TupleID> tuples = new HashSet<TupleID>();
	
	int icount = 0;
	/**
	 * 
	 */
	public UpdateAgent(HashMap<String, String> params,
			Long[][] array) {
		super(params.get("agentname"),Long.valueOf(params.get("meaninterval")),
				array);
		try {
			this.type = new TupleType(params.get("typename"));
			this.meaninterval = Long.valueOf(params.get("meaninterval"));
			//this.percentage = Double.valueOf(params.get("percentage"));
			this.mu = Long.valueOf(params.get("mu"));
			this.sigma = Long.valueOf(params.get("sigma"));
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Parameters are illegal.");
		}
		
		if (this.meaninterval < 0) {
			throw new IllegalArgumentException("Parameters are illegal.");
		}

		initialize();
	}
	
	private void initialize()
	{
		Timer timer = new Timer();
		TimerTask tt = new TimerTask() {
			@Override
			public void run() {
				timesup = true;
			}
		};
		
		timer.schedule(tt, AgentUtil.expTime);
//		Timer timer1 = new Timer();
//		TimerTask tt1 = new TimerTask() {
//			Runtime r = Runtime.getRuntime();
//			@Override
//			public void run() {
//				if(!timesup||icount==0){
//			     	LOG.info("Update Count " + agentName+" "+ type+ ":" + opCount);
//			     	LOG.info(agentName + " -> Total Memory: " + r.totalMemory()
//							+ "Used memory: " + (r.totalMemory() - r.freeMemory()));
//				}
//				if(timesup)
//					icount = 1;
//			}
//		};
//		
//		timer1.schedule(tt1,  DracoConstants.ADAPTATION_PERIOD,DracoConstants.ADAPTATION_PERIOD);
		
		dts = DracoTS.get("testing");
		ListReaction lr = new ListReaction(this);
		dts.addStrongReaction(new ListReaction[]{lr});
	}
	private RandomData randomData = new RandomDataImpl();
	private RandomData randomSize = new RandomDataImpl();
	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		super.run();
		
		sleepWait(AgentUtil.sleepTime);
		
		try {
			while(!timesup && getTuples().size()==0)
			{ 
				rest(0);
			}
			System.out.println(this.agentName+" Start working....");
			while (!this.timesup) {
				TupleID id = generateID();
				ShareTuple temp = ShareTuple.createVIDTemplate(id);
				temp.setReplica(false);
				temp.setCurr(Location.HERE);
				temp.setDest(Location.HERE);
				long begin = System.nanoTime();
				ShareTuple dt = (ShareTuple)dts.update(temp, createRandomTuple());
				long temp1 = System.nanoTime() - begin;
				 usedTotalTime += temp1; 
				if(dt!=null)
					if (dt != null) {
						LOG.info(String.format("UP,%s,vid=%s,replica=%b,size=%d,version=%d,optime=%g",
								agentName, 
								dt.getVID(), 
								dt.isReplica(),
								AbstractAgent.retriveDataSizeInTuple((FlatShareTuple)dt),
								dt.getVer(),
								temp1 / 1000000000.0));
					}
				else {
					LOG.info(String.format("UP,%s,FAIL,vid=%s", agentName,id));
				}
				opCount++;
				rest(temp1/1000000);
			}
			double timePerOp = usedTotalTime / 1000000000.0 / opCount;
			LOG.info(String.format("DONE,%s,optime=%g", getAgentName(), timePerOp));
			AgentServer.done();
		} catch (Exception ex) {
			System.out.println("Exception occurs : "
					+ Util.getExceptionDetail(ex));
			System.out
					.println(this.toString() + " Agent has been interrupted.");
		} finally {
			
		}
	}

	private TupleID generateID() {
		synchronized(tuples)
		{
			return  (TupleID)randomData.nextSample(tuples, 1)[0];
		}		
	}

//	private void rest() {
//		long sleeptime = (long) (randomData.nextExponential(1) * this.meaninterval);
//		try {
//			Thread.sleep(sleeptime);
//		} catch (InterruptedException e) {
//		
//			e.printStackTrace();
//		}
//		
//	}

	private HashSet<TupleID> getTuples() {
		synchronized(tuples)
		{
		return tuples;
		}
	}

	public String toString() {
		String id = "Agent Update " + ":" + Thread.currentThread().getName();
		String target = "Target type : " + type + " ;.";
		return id + ", " + target;
	}

	private Random random = new Random();

	private FlatShareTuple createRandomTuple()
	{
		double tupleSize = randomSize .nextGaussian(mu, sigma);
		byte []data = new byte[(int)tupleSize];
		if(data == null){
			System.out.println("Allocate failed!");
			System.exit(0);
		} else{
//			data[0] = 'b';
//			data[(int)tupleSize - 1] = 'z';
			random.nextBytes(data);
		}
		
//		String aString = new String(pChar);
		return makeNewTuple(type, data);
	}

	@Override
	public Location getTargetLocation() {
		
		return Location.HERE;
	}

	@Override
	public TupleType getType() {
		
		return type;
	}

	@Override
	public void updateList(ListTuple lt) {
		synchronized(tuples)
		{
			tuples.addAll(lt.getTupleList());
		}
		
	}

}
